// src/api/cart.ts
import request from './request.js';

// 定义数据结构
export interface CartItem {
  id: string | number;
  productId: string | number;
  name: string;
  price: number;
  count: number;
  imageUrl?: string;
  mainImage?: string;
  img?: string;
  image?: string;
  brand?: string;
  discountPrice?: number;
  userId?: number;
  amount?: number;
  number?: number;
}

// 分页参数接口
export interface CartListParams {
  pageNo: number;
  pageSize: number;
}

// 分页响应接口
export interface CartListResponse {
  items: CartItem[];
  total: number;
  pageNo: number;
  pageSize: number;
  totalPages: number;
}

// 后端返回的数据结构
export interface BackendCartResponse {
  code: number;
  message: string;
  data: {
    total: number;
    records: Array<{
      id: number;
      productId: number;
      name: string;
      image: string;
      userId: number;
      number: number;
      amount: number;
    }>;
  };
}

// 获取购物车列表（分页）
export async function getCartList(params: CartListParams = { pageNo: 1, pageSize: 10 }) {
  try {
    const response = await request.get<BackendCartResponse>('/shoppingCart/list', {
      params
    });

    // 数据格式转换
    const items = response.data.records.map((item: any) => ({
      id: item.id,
      productId: item.productId,
      name: item.name,
      price: item.amount, // amount 映射为 price
      count: item.number, // number 映射为 count
      image: item.image,
      mainImage: item.image,
      imageUrl: item.image,
      userId: item.userId,
      amount: item.amount,
      number: item.number
    }));

    // 计算总页数
    const totalPages = Math.ceil(response.data.total / params.pageSize);

    return {
      items,
      total: response.data.total,
      pageNo: params.pageNo,
      pageSize: params.pageSize,
      totalPages
    };
  } catch (error) {
    console.error('加载失败', error);
    throw new Error('加载失败');
  }
}

// 添加商品到购物车
export async function addToCart(productId: string | number, count: number = 1) {
  try {
    // 参数校验
    if (!productId || count <= 0) {
      throw new Error('Invalid parameters');
    }

    const { data } = await request.post<{ items: CartItem[] }>('/shoppingCart/add', {
      productId,
      count
    });

    return data.items;
  } catch (error) {
    console.error('加载失败', error);
    throw error;
  }
}

// 从购物车移除商品
export async function removeFromCart(productId: string | number) {
  try {
    if (!productId) {
      throw new Error('Product ID is required');
    }

    const { data } = await request.delete<{ items: CartItem[] }>(`/shoppingCart/${productId}`);

    return data.items;
  } catch (error) {
    console.error('加载失败', error);
    throw error;
  }
}

// 更新购物车商品数量
export async function updateCartItem(productId: string | number, count: number) {
  try {
    if (!productId || count <= 0) {
      throw new Error('Invalid parameters');
    }

    const { data } = await request.put<{ items: CartItem[] }>(`/shoppingCart/${productId}`, {
      count
    });

    return data.items;
  } catch (error) {
    console.error('加载失败', error);
    throw error;
  }
}

// 清空购物车
export async function clearCart() {
  try {
    await request.delete('/shoppingCart/clean');
    return true;
  } catch (error) {
    console.error('加载失败', error);
    throw error;
  }
}

// 批量删除购物车商品
export async function batchDeleteCartItems(ids: (string | number)[]) {
  try {
    if (!ids || ids.length === 0) {
      throw new Error('Product IDs are required');
    }

    const { data } = await request.delete<{ items: CartItem[] }>(`/shoppingCart?ids=${ids.join(',')}`);

    return data.items;
  } catch (error) {
    console.error('加载失败', error);
    throw error;
  }
}
